import socket
import multiprocessing
import re
import time
import dynamic.my_web


class WSGServer(object):
    def __init__(self,server_adderess):
        # Make a socket
        self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # allow to use port last time
        self.listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # bind
        self.listen_socket.bind(server_adderess)
        # listen
        self.listen_socket.listen(128)

    def server_forever(self):
        while True:
            client_socket, client_address = self.listen_socket.accept()
            print(client_address)
            new_process = multiprocessing.Process(target=self.handleRequest,args=(client_socket,))
            new_process.start()
            client_socket.close()

    def handleRequest(self,client_socket):
        recv_data = client_socket.recv(1024).decode()
        recv_data_headerlines = recv_data.splitlines()
        for line in recv_data_headerlines:
            print(line)
        request_line = recv_data_headerlines[0]
        get_filename = re.match(r"[^/]+(/[^ ]*)",request_line).group(1)
        if not get_filename.endswith('.py'):
            if get_filename == '/':
                get_filename = DOCUMENT_ROOT + "/index.html"
            else:
                get_filename = DOCUMENT_ROOT + get_filename

            try:
                f = open(get_filename, 'rb')
            except IOError:
                response_header = "HTTP/1.1 404 not found\r\n"
                response_header += '\r\n'
                response_body = "===========sorry,file not found=============="
            else:
                response_header = "HTTP/1.1 200 OK\r\n"
                response_header += '\r\n'
                response_body = f.read()
                f.close()
            finally:
                client_socket.send(response_header.encode('utf-8'))
                client_socket.send(response_body)
                client_socket.close()
        else:
            header = "HTTP/1.1 200 OK\r\n"
            header += '\r\n'
            # body = 'The Time:%s'% dynamic.my_web.login()
            body = dynamic.my_web.application(get_filename)
            response = header+body
            client_socket.send(response.encode('utf-8'))
            client_socket.close()



DOCUMENT_ROOT = './html'
SEVER_ADDR = (HOST, PORT) = "", 8889


def main():
    httpd = WSGServer(SEVER_ADDR)
    httpd.server_forever()

if __name__ == "__main__":
    main()